#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

using namespace std;

const int NUM=5;
int tickets=1000;

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

void *start_routine(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex); 
        // 判断暂时省略
        cout << name << " -> " << tickets <<endl;
        tickets--;
        pthread_mutex_unlock(&mutex);
    }
}


int main()
{
    pthread_t t[NUM];
    for(int i=0;i<NUM;i++)
    {

        // 线程名字 name 是局部变量 当循环时会被覆盖 可能导致线程访问无效内存
        // 应该为每个线程分配独立的名字存储空间
        //char name[64];
        char *name = new char[64];
        snprintf(name,64,"thread %d",i+1);
        pthread_create(&t[i],nullptr,start_routine,name);  
    }

    while (true)
    {
        sleep(1);
        //pthread_cond_signal(&cond); //唤醒至少一个等待该条件变量的线程
        pthread_cond_broadcast(&cond); //唤醒所有等待该条件变量的线程
        cout << "main thread wakeup one thread..." <<endl;
    }
    for (int i = 0; i < NUM; i++)
    {
        pthread_join(t[i], nullptr);
    }

    return 0;
}